package com.walleipt.ipt_tools.utils.gson;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;

import javax.xml.datatype.XMLGregorianCalendar;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.walleipt.ipt_tools.utils.DateUtils;

public class XMLGregorianCalendarAdapter implements JsonSerializer<XMLGregorianCalendar>, JsonDeserializer<XMLGregorianCalendar> {  
	  
    @Override  
    public XMLGregorianCalendar deserialize(JsonElement json, Type typeOfT,  
            JsonDeserializationContext context) throws JsonParseException {  
        if(json == null){  
            return null;  
        } else {  
            try {  
            	SimpleDateFormat formate = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ) ;
            	String value = json.getAsString() ;
                return DateUtils.toXMLGregorianCalendar( formate.parse( value ) );
            } catch (Exception e) {  
            	e.printStackTrace();
                return null;  
            }  
        }  
    }  
  
    @Override  
    public JsonElement serialize(XMLGregorianCalendar src, Type typeOfSrc,  
            JsonSerializationContext context) {  
        String value = "";  
        if(src != null){  
        	SimpleDateFormat formate = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ) ;
            value = String.valueOf(formate.format(DateUtils.XMLGregorianCalendar2Date(src)));  
        }  
        return new JsonPrimitive(value);  
    }  
      
}
